﻿using System.Configuration;
using System.Reflection;

namespace SimpleServiceBus.Configuration
{
    public class AssemblyConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string) base["name"]; }
        }

        public Assembly Assembly
        {
            get { return Assembly.Load(Name); }
        }

    }

    public class MessageAssemblyConfigurationElement: AssemblyConfigurationElement
    {
        [ConfigurationProperty("destinationAddress", IsRequired=false)]
        public string DestinationAddress
        {
            get { return (string) base["destinationAddress"]; }
        }
    }

    public class AssemblyConfigurationCollection : ConfigurationElementCollection
    {
        public AssemblyConfigurationElement this[int index]
        {
            get { return (AssemblyConfigurationElement) BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        protected override string ElementName
        {
            get { return "assembly"; }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new AssemblyConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((AssemblyConfigurationElement) element).Name;
        }
    }

    public class MessageAssemblyConfigurationCollection : AssemblyConfigurationCollection
    {
        public new MessageAssemblyConfigurationElement this[int index]
        {
            get { return (MessageAssemblyConfigurationElement) base[index]; }
            set { base[index] = value; }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new MessageAssemblyConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MessageAssemblyConfigurationElement)element).Name;
        }
    }
}